package com.gateway.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;

/**
 * 资源过滤器
 * @Author yin_q
 * @Date 2019/8/28 15:22
 * @Email yin_qingqin@163.com
 **/
@Configuration
@EnableResourceServer
public class SecurityConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private OAuth2WebSecurityExpressionHandler expressionHandler;

    /**
     * 白名单地址
     */
    private static final String[] AUTH_WHITELIST = {};

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 所有 /v2/api-docs   /uaa/** 这种url资源，任何角色都允许访问
        http.authorizeRequests().antMatchers("/v2/api-docs","/uaa/**").permitAll();

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();

        // 白名单里面的url资源任何角色都允许访问
        for(String url : AUTH_WHITELIST){
            http.authorizeRequests().antMatchers(url).permitAll();
        }

        // 其余url资源需要进行用户验证才能访问
        http.authorizeRequests().anyRequest().authenticated();
        registry.anyRequest().access("@permissionSvc.hasPermission(request, authentication)");
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.expressionHandler(expressionHandler);
    }

    @Bean
    public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
        OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
        expressionHandler.setApplicationContext(applicationContext);
        return expressionHandler;
    }
}
